/**
 * Created by oneminute on 8/11/14.
 */
var program = require('commander');
var lz = require("../lib/utils/modules")();

program
    .version('0.0.1')
    .option('-p, --port [port]', 'Application Port.')
    .parse(process.argv);


var http = require('http'),
    httpProxy = require('http-proxy');

//
// Create a proxy server with latency
//
var proxy = httpProxy.createProxyServer({
    target: 'ws://localhost:9008/chat',
    ws: true
});

//
// Create your server that make an operation that take a while
// and then proxy de request
//
http.createServer(function (req, res, head) {
    // This simulate an operation that take 500ms in execute
    var path = req.url.split("\?")[0];
    lz.Logger.debug(req.url.split("\?")[0]);
    lz.Logger.debug(head);
    if (path == "/chat") {
        proxy.ws(req, res, head);
    } else {
        proxy.web(req, res, {
            target: 'http://localhost:9008'
        });
    }
}).listen(3050);

httpProxy.createServer({
    target: 'ws://localhost:9008/chat',
    ws:true
}).listen(13050);

var express = require("express");
var Server = require('socket.io');
var app = express();
app.all("/index.html", function (_req, _res) {
    lz.Logger.debug("/index.html: invoke.");
    _res.end();
});
var httpServer = http.createServer(app);
var io = Server(httpServer);
var nsp = io.of("/chat");
//io.path("/socket.io");
nsp.on('connection', function (_socket) {
    console.log('a new connection founded. id: ' + _socket.id);
    _socket.send('欢迎来到乐众聊天室。', function (_confirmed) {
        console.log('ack: ' + _confirmed);
    });
    _socket.on('iwant.connect', function (_data, _ack) {
        console.log('receive msg: ' + _data.uid);
        if (_data.uid) {
            _ack({res: true});
        } else {
            _ack({res: false, reason: '没有提供有效的uid'});
        }

    });
    _socket.on('iwant.message', function (_data, _ack) {
        console.log('iwant.message: ' + JSON.stringify(_data));
        _ack(true);
        /*_socket.emit('iwant.message', _data, function() {
         console.log('iwant.message: 响应消息。');
         });*/
    });
    _socket.on('disconnect', function () {
        console.log('disconnect: ');
    });
    _socket.on('error', function (_err) {
        console.log('error: ' + _err);
    });
    _socket.on('message', function (_data) {
        console.log('message: ' + JSON.stringify(_data));
    });
});
//
// Create your target server
//
httpServer.listen(9008);

